package com.renwenhao.filtertest;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("登录校验");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");
        String path = request.getRequestURI();
        if (path.startsWith("/static/")
                || path.contains("/checkCodeServlet")
                || path.contains("/loginServlet")
                || path.contains("/jsp/login.jsp")
                || path.contains("/jsp/register.jsp")) {
            chain.doFilter(req, resp);
        } else {
            if (user != null) {
                chain.doFilter(req, resp);
            } else {
                ((HttpServletResponse) resp).sendRedirect("/jsp/login.jsp");
            }
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
